<template>
    <div>
        <!--        面包屑导航栏-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--        显示面板-->
        <el-card>
            <el-alert
                    title="注意：只允许为第三级分类设置相关参数!"
                    :closable="false"
                    show-icon
                    type="warning">
            </el-alert>
            <el-row class="selectGoods">
                <el-col>
                    <span>请选择商品分类:</span>
                    <!--                    级联选择器-->
                    <el-cascader
                            clearable
                            style="width: 300px"
                            v-model="selectedIds"
                            :options="cateList"
                            :props="cateListProps"
                            @change="handleChange"></el-cascader>
                </el-col>
            </el-row>
            <!--            tabs标签页-->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">
                        添加参数
                    </el-button>
                    <!--                    表格-->
                    <el-table :data="manyTableData" border stripe>
                        <!--                        展开列-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable
                                        @close="handleClose(index,scope.row)">{{item}}
                                </el-tag>
                                <!--                                添加文本框与按钮-->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="参数名称" align="center" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑
                                </el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">
                        添加参数
                    </el-button>
                    <el-table :data="onlyTableData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable
                                        @close="handleClose(index,scope.row)">{{item}}
                                </el-tag>
                                <!--                                添加文本框与按钮-->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="#"></el-table-column>
                        <el-table-column label="属性  名称" align="center" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑
                                </el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!--        添加参数对话框-->
        <el-dialog
                @close="addDialogClosed"
                :title="activeName === 'many' ? '添加动态参数' : '添加静态属性'"
                :visible.sync="addDialogVisible"
                width="50%"
        >
            <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="activeName === 'many' ? '动态参数' : '静态属性'" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
        </el-dialog>
        <!--        编辑对话框-->
        <el-dialog
                @close="editDialogClosed"
                :title="activeName === 'many' ? '修改动态参数' : '修改静态属性'"
                :visible.sync="editDialogVisible"
                width="50%"
        >
            <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="activeName === 'many' ? '动态参数' : '静态属性'" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "Params",
        data() {
            return {
                cateList: [],
                // 级联选择
                cateListProps: {
                    expandTrigger: 'hover',
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children'
                },
                selectedIds: '',
                // tabs标签页
                activeName: "many",
                manyTableData: [],
                onlyTableData: [],
                // 添加属性对话框
                addDialogVisible: false,
                addForm: {
                    attr_name: ''
                },
                addRules: {
                    attr_name: [
                        {required: true, message: '请输入参数', trigger: 'blur'},
                    ]
                },
                // 编辑
                editDialogVisible: false,
                editForm: {
                    attr_name: '',
                    attributeId: ''
                },
                editRules: {
                    attr_name: [
                        {required: true, message: '请输入参数', trigger: 'blur'},
                    ]
                },
            }
        },
        created() {
            this.getCateList()
        },
        methods: {
            async getCateList() {
                const res = (await this.$http.get('categories', {params: {type: 3}})).data
                if (res.meta.status !== 200) {
                    return this.$message.error({
                        message: '获取商品分类列表失败!',
                        center: true
                    })
                } else {
                    this.cateList = res.data
                }
            },
            handleChange() {
                this.getParamsData()
            },
            handleClick() {
                this.getParamsData()
            },
            async getParamsData() {
                if (this.selectedIds.length !== 3) {
                    this.selectedIds = []
                    this.manyTableData = []
                    this.onlyTableData = []
                    return
                } else {
                    const res = (await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}})).data
                    if (res.meta.status !== 200) {
                        return this.$message.error({
                            message: "请求分类参数失败！",
                            center: true
                        })
                    } else {
                        res.data.forEach(item => {
                            item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : []
                            item.inputVisible = false
                            item.inputValue = ''
                        })
                        if (this.activeName === 'many') {
                            this.manyTableData = res.data
                        } else {
                            this.onlyTableData = res.data
                        }
                    }
                }
            },
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()
            },
            async addParams() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) {
                        return
                    } else {
                        const res = (await this.$http.post(`categories/${this.cateId}/attributes`, {
                            attr_name: this.addForm.attr_name,
                            attr_sel: this.activeName
                        })).data
                        if (res.meta.status !== 201) {
                            console.log(res);
                            return this.$message.error({
                                message: '添加失败!',
                                center: true
                            })
                        } else {
                            this.$message.success({
                                message: '添加成功!',
                                center: true
                            })
                            await this.getParamsData()
                            this.addDialogVisible = false
                        }
                    }
                })
            },
            editDialogClosed() {
                this.$refs.editFormRef.resetFields()
            },
            showEditDialog(info) {
                this.editDialogVisible = true
                this.editForm.attr_name = info.attr_name
                this.editForm.attributeId = info.attr_id
            },
            editParams() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) {
                        return
                    } else {
                        const res = (await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attributeId}`, {
                            attr_name: this.editForm.attr_name,
                            attr_sel: this.activeName
                        })).data
                        if (res.meta.status !== 200) {
                            return this.$message.error({
                                message: '修改失败!',
                                center: true
                            })
                        } else {
                            this.$message.success({
                                message: '修改成功!',
                                center: true
                            })
                            this.editDialogVisible = false
                            await this.getParamsData()
                        }
                    }
                })
            },
            deleteParams: async function (attr_id) {
                const info = await this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (info == 'cancel') {
                    return this.$message.info({
                        message: '已取消删除!',
                        center: true
                    })
                } else {
                    const res = (await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)).data
                    if (res.meta.status !== 200) {
                        return this.$message.error({
                            message: '删除失败!',
                            center: true
                        })
                    } else {
                        this.$message.success({
                            message: '删除成功!',
                            center: true
                        })
                        await this.getParamsData()
                    }
                }
            },
            // 文本输入框与按钮的切换
            handleInputConfirm(row) {
                if (row.inputValue.trim().length === 0) {
                    row.inputValue = ''
                    row.inputVisible = false
                    return
                } else {
                    row.attr_vals.push(row.inputValue.trim())
                    row.inputValue = ''
                    this.saveAttrVals(row)
                }
            },
            showInput(row) {
                row.inputVisible = true
                // 自动获取焦点
                // 当页面的元素重新渲染之后才会执行￥nextTick回调函数里面的代码
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            async saveAttrVals(row) {
                const res = (await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                })).data
                console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error({
                        message: '修改参数项失败！',
                        center: true
                    })
                } else {
                    this.$message.success({
                        message: '修改参数项成功!',
                        center: true
                    })
                }
            },
            handleClose(index, row) {
                // 删除数组中的元素
                row.attr_vals.splice(index, 1)
                this.saveAttrVals(row)
            }
        },
        computed: {
            isBtnDisabled() {
                if (this.selectedIds.length !== 3) {
                    return true
                } else {
                    return false
                }
            },
            // 获取三级分类的ID
            cateId() {
                if (this.selectedIds.length == 3) {
                    return this.selectedIds[2]
                } else {
                    return null
                }
            }
        }
    }
</script>

<style scoped>
    .selectGoods {
        margin: 15px 0;
    }

    .el-col span {
        margin-right: 15px;
    }

    .el-tag {
        margin-right: 10px;
    }

    .input-new-tag {
        width: 120px;
    }
</style>